#include "Controller.h"

Controller::Controller()
{
	mouse_locked = true;
	keystate = NULL;
	SDL_ShowCursor(!mouse_locked); //hide or show the mouse /////////////// no estoy seguroooooooo
}

Controller::~Controller(void)
{
}

void Controller::mouseMovement()
{
	if (mouse_locked)
	{
		SDL_WarpMouse(WINDOW_WIDTH*0.5, WINDOW_HEIGHT*0.5); //put the mouse back in the middle of the screen
		this->mouse_position.x = WINDOW_WIDTH*0.5;
		this->mouse_position.y = WINDOW_HEIGHT*0.5;
	}
	player->model.rotateLocal((mouse_position.y-WINDOW_HEIGHT/2)/WINDOW_HEIGHT*0.02, Vector3(-1,0,0));
	player->model.rotateLocal((mouse_position.x-WINDOW_WIDTH/2)/WINDOW_WIDTH*0.02, Vector3(0,1,0));
}

//Keyboard event handler (sync input)
void Controller::onKeyPressed( SDL_KeyboardEvent event )
{
	switch(event.keysym.sym)
	{
		case SDLK_ESCAPE: exit(0);
		//case SDLK_c: cam_pos = (cam_pos == CABINA)?COLA:CABINA;
	}
}


void Controller::onMouseButton( SDL_MouseButtonEvent event )
{
	if (event.button == SDL_BUTTON_MIDDLE)
	{
		mouse_locked = !mouse_locked;
		SDL_ShowCursor(!mouse_locked);
	}
}

void Controller::update(float seconds_elapsed)
{
	SDL_GetMouseState(&x,&y);
	mouse_position.set(x,y);

		//update events
		while(SDL_PollEvent(&sdlEvent))
		{
			switch(sdlEvent.type)
				{
					case SDL_QUIT: return; break; //EVENT for when the user clicks the [x] in the corner
					case SDL_MOUSEBUTTONDOWN: //EXAMPLE OF sync mouse input
						onMouseButton( sdlEvent.button );
						break;
					case SDL_MOUSEBUTTONUP:
						//...
						break;
					case SDL_KEYDOWN: //EXAMPLE OF sync keyboard input
						onKeyPressed( sdlEvent.key );
						break;
				}
		}
		//read keyboard state and stored in keystate
		mouse_state = SDL_GetMouseState(&x,&y);
		keystate = SDL_GetKeyState(NULL);
		
		//get mouse position and delta
		mouse_delta.set( mouse_position.x - x, mouse_position.y - y );
		mouse_position.set(x,y);

	//async input to move the camera around
	if(keystate[SDLK_LSHIFT]) player->aceleration(player->speed); 
	if(keystate[SDLK_w])
	{
		if(mouse_locked) mouse_locked=player->takeOff(seconds_elapsed);
		else player->straight(player->model,player->speed); 

	}
	if(keystate[SDLK_a]) player->left(player->model,seconds_elapsed);
	if(keystate[SDLK_d]) player->right(player->model,seconds_elapsed);
	if(keystate[SDLK_SPACE]) player->fire();
	if(keystate[SDLK_p]) for(int i=0; i<16; i++) std::cout << player->model.m[i] << " " << std::endl;
}

